package com.quanyan.club.service.impl;

import com.quanyan.activity.response.RespActivityPoster;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.RespClubBaseInfo;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.ReqClubActivityCondition;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.entity.vo.resp.RespClubActivityGame;
import com.quanyan.club.entity.vo.resp.RespClubHomePage;
import com.quanyan.club.entity.vo.resp.RespClubHomePageMore;
import com.quanyan.club.entity.vo.resp.movement.RespClubIntegralRank;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.*;
import com.quanyan.club.thread.ClubMemberSolrIndexThread;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.search.service.impl.ActivitySearchServiceImpl;
import com.quanyan.search.service.impl.ClubMemberSearchServiceImpl;
import com.quanyan.search.service.impl.ClubSearchServiceImpl;
import com.quanyan.statium.api.resp.ResGameEvent;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhuo.shi on 2016/11/8.
 *
 * 俱乐部主页接口
 */
@Service
public class ClubHomePageServiceImpl extends BaseServiceImpl implements ClubHomePageService{

    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbActivityMapper activityMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbClubOnlineAccountMapper clubOnlineAccountMapper;
    @Autowired
    private TbClubMemberApplyMapper clubMemberApplyMapper;
    @Autowired
    private TbClubAnnouncementMapper clubAnnouncementMapper;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Value("${club_share_url}")
    private String clubShareUrl;
    @Value("${o.new.url}")
    private String oldBringNewUrl;  //老带新url
    @Autowired
    private TbClubOnlineMemberAccountMapper clubOnlineMemberAccountMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbClubMultimediaMapper clubMultimediaMapper;
    @Autowired
    private TbClubActivityMapper clubActivityMapper;
    @Autowired
    private TbActivityPosterMapper posterMapper;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private TbClubOfflineMemberAccountMapper clubOfflineMemberAccountMapper;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private CppService cppService;
    @Autowired
    private TbActivityPosterMapper activityPosterMapper;
    @Autowired
    private ClubActivityService clubActivityService;
    @Autowired
    private ActivityCRUDService activityCRUDService;
    @Autowired
    private TbClubActivitySettlementMapper clubActivitySettlementMapper;
    @Autowired
    private ClubActivityMapper customeClubActivityMapper;
    @Autowired
    private TbSignUserMapper signUserMapper;

    @Autowired
    private ClubIntegralService clubIntegralService;

    private ClubMemberSearchServiceImpl clubMemberSearchService;
    @PostConstruct
    protected  void initClubMemberSearch(){
        clubMemberSearchService = new ClubMemberSearchServiceImpl();
        clubMemberSearchService.setURL(searchCloudUrl);
    }

    private ActivitySearchServiceImpl activitySearchService;
    @PostConstruct
    protected void initActivitySearch(){
        activitySearchService = new ActivitySearchServiceImpl();
        activitySearchService.setURL(searchCloudUrl);
    }

    private ClubSearchServiceImpl clubSearchService;
    @PostConstruct
    protected  void initClubSearch(){
        clubSearchService = new ClubSearchServiceImpl(searchCloudUrl);
    }

    private Logger logger = LoggerFactory.getLogger(ClubHomePageServiceImpl.class);

    @Override
    public RespClubHomePage index(Integer currentUid, int clubId) {

        RespClubHomePage homePage = new RespClubHomePage();

        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub == null){
            return homePage;
        }
        if (tbClub.getIsDelete() == Constants.IS_DELETE_TRUE){
            throw new BizException("此俱乐部已被暂停！");
        }

        //基本信息
        homePage.setClubId(tbClub.getId());
        homePage.setLogo(tbClub.getLogoUrl());
        homePage.setBgUrl(tbClub.getBgUrl());
        homePage.setClubName(tbClub.getClubName());
        homePage.setResidentPlaceName(tbClub.getResidentPlaceName());
        int cityId = tbClub.getCityId();
        homePage.setCityId(cityId);
        homePage.setCityName(getCity(cityId)==null?"":getCity(cityId).getName());
        int districtId = tbClub.getDistrictId();
        homePage.setDistrictId(districtId);
        homePage.setDistrictName(getDistrict(districtId)==null?"":getDistrict(districtId).getName());
        RespClubIntegralRank integralRank = clubIntegralService.getClubIntegralRankByClubId(clubId, tbClub.getClubType());
        if (integralRank != null) {
            BigDecimal star = new BigDecimal(integralRank.getClubStar());
            star = star.setScale(1, BigDecimal.ROUND_HALF_UP);      //只保留一位小数，四舍五入
            homePage.setStar(star.doubleValue());
            homePage.setIntegral(integralRank.getClubIntegral());
            int integralSwitch = clubIntegralService.getIntegralSwitch().intValue();
            homePage.setIntegralSwitch(integralSwitch==1);
            homePage.setRanking(integralRank.getClubRank());        //全国排名
        }
        homePage.setOpenMembers(tbClub.getOpenMembers());
        homePage.setRealNameAuth(isRealNameAuthClub(clubId));   //是否实名认证

        //分享链接
        StringBuilder sb = new StringBuilder();
        sb.append(clubShareUrl).append("?").append("clubId=").append(clubId);
        homePage.setShareUrl(sb.toString());
//        homePage.setOldBringNewUrl(oldBringNewUrl);

        //聊天，公告
        homePage.setImGroupId(tbClub.getImGroupid());       //聊天室id
        homePage.setAnnouncement(this.getLatestClubAnnouncement(clubId));       //最新一条公告

        //成员人数
        TbClubMemberExample clubMemberExample = new TbClubMemberExample();
        clubMemberExample.createCriteria()
                .andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(clubMemberExample);
        List<Integer> uids = new ArrayList<>();
        for (TbClubMember clubMember : clubMembers){
            uids.add(clubMember.getUid());
        }
        int maleCount = 0, femaleCount = 0;
        APIResponse<List<RespUserInfoBase>> response = userServiceFacade.batchQueryUserInfo(uids);
        if (response != null && response.isRet()){
            List<RespUserInfoBase> userInfoList = response.getData();
            for (RespUserInfoBase userInfo : userInfoList){
                int gender = userInfo.getGender();
                if (gender == 1){ //男
                    maleCount += 1;
                }
                if (gender == 2){ //女
                    femaleCount += 1;
                }
            }
        }
        homePage.setMemberCount(clubMembers.size());
        homePage.setMaleCount(maleCount);
        homePage.setFemalCount(femaleCount);

        //栏目类型
        homePage.setSportTypeId(tbClub.getClubType());
        homePage.setSportTypeName(tbClub.getSportName());

        RespUserInfoDetail userInfoBase = getUserDetailInfo(tbClub.getUid());
        if (userInfoBase != null){
            //实名认证状态：0为未认证，1为认证中，2为认证通过，3为认证失败
            homePage.setIdentityStatus(userInfoBase.getNameVerifyStatusDe());
        }else {
            homePage.setIdentityStatus((byte)0);
        }

        homePage.setJoinType((int)tbClub.getJoinType());        //加入俱乐部是否需要审核
        if (currentUid != null && currentUid != 0) {
            //申请加入俱乐部的审核状态：-1 没有申请 0 未审核 1 审核通过 2 审核拒绝
            homePage.setJoinStatus(clubMemberService.getJoinClubStatus(clubId, currentUid));
            boolean isJoin = clubMemberService.isClubMember(currentUid, clubId);
            homePage.setJoin(isJoin);
            //在此俱乐部的角色编码
            String roleCode = getRoleCode(clubId, currentUid);
            homePage.setRoleCode(roleCode);
            if (Constants.ClubRole.CLUB_ROLE_PRESIDENT.equals(roleCode)
                    || Constants.ClubRole.ROLE_CLUB_FINANCIAL.equals(roleCode) || Constants.ClubRole.ROLE_CLUB_ADMIN.equals(roleCode)){
                //可提现金额
                TbClubOnlineAccountExample accountExample = new TbClubOnlineAccountExample();
                accountExample.createCriteria()
                        .andClubIdEqualTo(clubId)
                        .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                List<TbClubOnlineAccount> onlineAccounts = clubOnlineAccountMapper.selectByExample(accountExample);
                if (onlineAccounts != null && onlineAccounts.size() > 0){
                    homePage.setUsableWithdrawAmount(onlineAccounts.get(0).getMoneyUsable());
                }
                //最近一笔未结算的活动收入
                homePage.setUnsettlementAmount(getLastSettlementActivityAmount(clubId));
                //最近发布活动的天数、未结算的活动数、本周增加的俱乐部成员数、本周收入
                homePage.setDate4ActivityPublish(getLastPublishActivityDates(clubId));
                Integer unsettleActivityCount = customeClubActivityMapper.countUnsettleActivityNum(clubId);
                homePage.setCount4UnsettlementActivity(unsettleActivityCount==null?0:unsettleActivityCount);
                homePage.setCount4MemberIncrThisWeek(getIncrMemberCountThisWeek(clubId));
                homePage.setTotalAmount4ThisWeek(getIncomeAmountThisWeek(clubId));
            }
        }

        return homePage;
    }

    /**
     * 距离上次发布活动的天数
     */
    private int getLastPublishActivityDates(int clubId){
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        example.setOrderByClause(" create_time desc");
        List<TbClubActivity> activities = clubActivityMapper.selectByExample(example);
        if (activities == null || activities.size() == 0) {
            //QAAPP-1656未创建过活动，创建活动下的文案不显示
            return -1;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date createTime = activities.get(0).getCreateTime();
        try {
            createTime = sdf.parse(sdf.format(createTime));
            Date now = new Date();
            now = sdf.parse(sdf.format(now));
            long days = (now.getTime() - createTime.getTime())/(1000*3600*24);
            return Integer.parseInt(String.valueOf(days));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 俱乐部未结算的活动个数
     */
//    private int getUnsettlementActivityCount(int clubId){
//        TbClubActivityExample example = new TbClubActivityExample();
//        example.createCriteria()
//                .andClubIdEqualTo(clubId)
//                .andIsSettleIn(Arrays.asList(new Byte[]{0, 2})); // 未结算的活动: 状态 0 未结算 1 已结算 2现场管理已提交(未结算)
//        return clubActivityMapper.countByExample(example);
//    }

    /**
     * 最近一笔未结算的活动收入总金额
     */
    private BigDecimal getLastSettlementActivityAmount(int clubId){

        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsSettleIn(Arrays.asList(new Byte[]{0, 2}));
        example.setOrderByClause("create_time desc");
        List<TbClubActivity> activities = clubActivityMapper.selectByExample(example);
        if (activities == null || activities.size() == 0){
            return BigDecimal.ZERO;
        }

        for (TbClubActivity tbClubActivity : activities) {

            BigDecimal totalAmount = BigDecimal.ZERO;

            int activityId = tbClubActivity.getActivityId();
            TbActivity tbActivity = activityMapper.selectByPrimaryKey(activityId);
            if (tbActivity == null || tbActivity.getEndTime().after(new Date())){  //还未结束了的活动排除
                continue;
            }

            TbOrderExample orderExample = new TbOrderExample();
            orderExample.createCriteria()
                    .andActivityIdEqualTo(activityId)
                    .andOrderStatusIn(Arrays.asList((byte) 2, (byte) 6, (byte) 7))
                    .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbOrder> orders = orderMapper.selectByExample(orderExample);
            if (orders == null || orders.size() == 0) {
                continue;
            }

            for (TbOrder tbOrder : orders) {
                totalAmount = totalAmount.add(calculateOrderAmount(tbOrder));
            }
            if (totalAmount.doubleValue() != 0){
                return totalAmount;
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * 计算一个订单中排除请假、不请假的订单金额
     */
    private BigDecimal calculateOrderAmount(TbOrder tbOrder){

        TbSignUserExample example = new TbSignUserExample();
        example.createCriteria().andOrderIdEqualTo(tbOrder.getId())
                .andManageTypeIn(Arrays.asList(1, 2));

        Integer uCount = signUserMapper.countByExample(example);        //这个订单中，请假，补请假的人数

        BigDecimal orderAmount = tbOrder.getOrderAmount();
//        BigDecimal avgAmount = orderAmount.divide(new BigDecimal(tbOrder.getApplyNum()), BigDecimal.ROUND_DOWN);
//        orderAmount = orderAmount.subtract(avgAmount.multiply(new BigDecimal(uCount)));
        if (uCount>0){      //有请假或补请假，这个订单准备退款，待结算金额为0
            return new BigDecimal(0);
        }

        return orderAmount;
    }

    /**
     * 俱乐部本周新增成员人数
     */
    private int getIncrMemberCountThisWeek(int clubId){

        Date now = new Date();      //当前时间
        Date thisWeekMondayBegin = DateUtils.dayBegin(DateUtils.getMondayOfWeek(now, 0));       //这周一的凌晨0点

        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andCreateTimeGreaterThanOrEqualTo(thisWeekMondayBegin)
                .andCreateTimeLessThan(now)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        return clubMemberMapper.countByExample(example);
    }

    /**
     * 俱乐部这周收入金额
     */
    private BigDecimal getIncomeAmountThisWeek(int clubId){

        Date now = new Date();      //当前时间
        Date thisWeekMondayBegin = DateUtils.dayBegin(DateUtils.getMondayOfWeek(now, 0));       //这周一的凌晨0点
        Date thisWeekSundayEnd = DateUtils.dayEnd(DateUtils.getSundayOfWeek(now, 0));         //这周周日晚上23:59:59

        TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andCreateTimeGreaterThanOrEqualTo(thisWeekMondayBegin)
                .andCreateTimeLessThan(thisWeekSundayEnd);
        List<TbClubActivitySettlement> settlements =  clubActivitySettlementMapper.selectByExample(example);
        if (settlements == null || settlements.size() == 0){
            return BigDecimal.ZERO;
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        for (TbClubActivitySettlement settlement : settlements){
            totalAmount = totalAmount.add(settlement.getDealMoney());
        }

        return totalAmount;
    }

    /**
     * 俱乐部排名
     */
    private int getClubRanking(Integer clubId){
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        if(null == club){
            return 0;
        }
        Map<String, Object> paramMap = new HashMap<>();
        Integer sportTypeId = club.getClubType();
        if (sportTypeId != null){
            paramMap.put("sportTypeId", sportTypeId);
        }
        List<RespClubBaseInfo> list = sqlSessionTemplate.selectList("selectClubRankingList", paramMap);
        if (list != null && list.size() > 0){
            for (RespClubBaseInfo clubBaseInfo : list){
                if (clubBaseInfo.getClubId().intValue() == clubId){
                    return clubBaseInfo.getRanking();
                }
            }
        }
        return 0;
    }

    /**
     * 用户在俱乐部中的角色
     */
    private String getRoleCode(int clubId, int uid){
        //在此俱乐部的角色编码
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId).andUidEqualTo(uid).andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubMember> tbClubMembers = clubMemberMapper.selectByExample(example);
        if (tbClubMembers != null && tbClubMembers.size() != 0) {
            return tbClubMembers.get(0).getRoleCode();
        }
        return null;
    }

    /**
     * 最新一条公告
     */
    private TbClubAnnouncement getLatestClubAnnouncement(Integer clubId){
        TbClubAnnouncementExample clubAnnouncementExample = new TbClubAnnouncementExample();
        clubAnnouncementExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo((int) Constants.IS_DELETE_FALSE);
        clubAnnouncementExample.setOrderByClause(" create_time desc");
        List<TbClubAnnouncement> clubAnnouncements =
                clubAnnouncementMapper.selectByExample(clubAnnouncementExample);
        if (clubAnnouncements == null || clubAnnouncements.size() == 0){
           return null;
        }
        return clubAnnouncements.get(0);
    }

    @Override
    public RespClubHomePageMore detail(Integer currentUid, int clubId) {

        RespClubHomePageMore homePageMore = new RespClubHomePageMore();

        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub == null){
            return homePageMore;
        }
        if (tbClub.getIsDelete() == 1){
            throw new BizException("此俱乐部已被暂停！");
        }

        homePageMore.setClubId(tbClub.getId());
        homePageMore.setClubName(tbClub.getClubName());
        homePageMore.setJoinType((int)tbClub.getJoinType());
        homePageMore.setOpenMembers(tbClub.getOpenMembers());
        homePageMore.setFoundDate(tbClub.getFoundDate());
        homePageMore.setResidentPlaceId(tbClub.getResidentPlaceId());
        homePageMore.setResidentPlaceName(tbClub.getResidentPlaceName());
        homePageMore.setCityName(getCity(tbClub.getCityId())==null?"":getCity(tbClub.getCityId()).getName());
        homePageMore.setDistrictName(getDistrict(tbClub.getDistrictId())==null?"":getDistrict(tbClub.getDistrictId()).getName());
        TbClubProperty cp1 = getClubProperty(tbClub.getClubPropertyId()); //一级属性
        TbClubProperty cp2 = getClubProperty(tbClub.getClubPropertyChildId()); //二级属性
        if (cp1 != null) {
            homePageMore.setClubProperty(cp1.getPropertyName());
        }
        if (cp2 != null) {
            homePageMore.setClubChildProperty(cp2.getPropertyName());
        }
        homePageMore.setHomeTeamColor(tbClub.getHomeTeamColor());
        homePageMore.setGuestTeamColor(tbClub.getGuestTeamColor());
        homePageMore.setIntroduce(tbClub.getIntroduce());
        homePageMore.setPurpose(tbClub.getPurpose());
        homePageMore.setClubType(tbClub.getClubType());
        homePageMore.setLogo(tbClub.getLogoUrl());
        homePageMore.setRoleCode(getRoleCode(clubId, currentUid));

        if (currentUid != 0) {
            TbClubOnlineMemberAccountExample example = new TbClubOnlineMemberAccountExample();
            example.createCriteria()
                    .andClubIdEqualTo(clubId)
                    .andUidEqualTo(currentUid)
                    .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbClubOnlineMemberAccount> clubOnlineMemberAccounts = clubOnlineMemberAccountMapper.selectByExample(example);
            if (clubOnlineMemberAccounts != null && clubOnlineMemberAccounts.size() != 0) {
                homePageMore.setClubMemberFund(clubOnlineMemberAccounts.get(0).getMoneyTotal());
            }
        }

        return homePageMore;
    }

    @Override
    public List<TbClubMultimedia> photoList(int clubId) {
        TbClubMultimediaExample multimediaExample = new TbClubMultimediaExample();
        multimediaExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        multimediaExample.setOrderByClause(" create_time desc");
        return clubMultimediaMapper.selectByExample(multimediaExample);
    }

    @Override
    public RespClubActivityGame activityList(Integer currentUid, int clubId) {

        RespClubActivityGame clubActivityGame = new RespClubActivityGame();
        clubActivityGame.setClubId(clubId);
        //只取3个赛事
        List<ResGameEvent> games = null;
//        try {
//            games = stadiumOpenService.getResGameEventsByClubId(clubId, 3);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        if (games == null){
            games = new ArrayList<>();
//        }
        clubActivityGame.setGame(games);

        //当前用户是否是此俱乐部管理员
        boolean isClubAdmin = clubMemberService.isClubAdminMember(currentUid, clubId);

        ReqClubActivityCondition condition = new ReqClubActivityCondition();
        condition.setClubId(clubId);
        condition.setPageNum(0);
        condition.setPageSize(2);
        PageObj<List<RespClubActivity>> pageObj = activityCRUDService.clubActivityListByCriteria(condition, currentUid);
        clubActivityGame.setActivity(pageObj.getItems());

//        TbClubActivityExample activityExample = new TbClubActivityExample();
//        activityExample.createCriteria()
//                .andClubIdEqualTo(clubId)
//                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
//        activityExample.setOrderByClause(" create_time desc");
//        List<TbClubActivity> clubActivityList = clubActivityMapper.selectByExample(activityExample);
//        if(clubActivityList == null || clubActivityList.size() == 0) {
//            return clubActivityGame;
//        }
//        List<ActivityInfo> resultList = new ArrayList<>();
//        for (TbClubActivity tbClubActivity : clubActivityList){
//            Integer activityId = tbClubActivity.getActivityId();
//            ActivityInfo activityInfo = activityOpenService.selectOneActivityById(activityId);
//            activityInfo.setCurTime(new Date());
//            activityInfo.setPrice(getActivityMinPrice(tbClubActivity));
//            activityInfo.setRespActivityPoster(getActivityPoster(activityInfo.getPosterPicId()));
//            int status = activityInfo.getStatus();          //活动状态
//            long currentTime = System.currentTimeMillis();
//            if (status == 2 || status == 1){    //1 暂停， 2 取消
//                if (!isClubAdmin) continue;
//            }else {
//                if (currentTime < activityInfo.getSignEndTime().getTime()){
//                    if (activityInfo.getLimitNum().intValue() == activityInfo.getAlreadySignTotalNum().intValue() && activityInfo.getLimitNum() != 0) { //已报满
//                        if (!isClubAdmin) continue;
//                    } else {
//                         //报名中
//                    }
//                } else if (currentTime > activityInfo.getSignEndTime().getTime() && currentTime < activityInfo.getStartTime().getTime()) {//报名截止
//                    if (!isClubAdmin) continue;
//                } else if (currentTime > activityInfo.getStartTime().getTime() && currentTime < activityInfo.getEndTime().getTime()) { //活动进行中
//                    if (!isClubAdmin) continue;
//                } else if (currentTime > activityInfo.getEndTime().getTime()) { //活动已经结束
//                    if (!isClubAdmin) continue;
//                }
//            }
//            resultList.add(activityInfo);
//        }

        //只取2个活动
//        if (resultList.size() > 2){
//            clubActivityGame.setActivity(resultList.subList(0, 2));
//        }else {
//            clubActivityGame.setActivity(resultList);
//        }

        return clubActivityGame;
    }

    /**
     * 根据俱乐部角色判断是否显示活动
     */
    private List<RespClubActivity> filter(boolean isClubAdmin, List<RespClubActivity> list){
        if (list == null){
            return list;
        }
        Iterator<RespClubActivity> it = list.iterator();
        while (it.hasNext()) {
            RespClubActivity clubActivity = it.next();
            int status = clubActivity.getStatus();          //活动状态
            long currentTime = System.currentTimeMillis();
            if (status == 2 || status == 1) {    //1 暂停， 2 取消
                if (!isClubAdmin) it.remove();
            } else {
                if (currentTime < clubActivity.getSignEndTime().getTime()) {
                    if (clubActivity.getLimitNum().intValue() == clubActivity.getAlreadySignTotalNum().intValue() && clubActivity.getLimitNum() != 0) { //已报满
                        if (!isClubAdmin) it.remove();
                    } else {
                        //报名中
                    }
                } else if (currentTime > clubActivity.getSignEndTime().getTime() && currentTime < clubActivity.getStartTime().getTime()) {//报名截止
                    if (!isClubAdmin) it.remove();
                } else if (currentTime > clubActivity.getStartTime().getTime() && currentTime < clubActivity.getEndTime().getTime()) { //活动进行中
                    if (!isClubAdmin) it.remove();
                } else if (currentTime > clubActivity.getEndTime().getTime()) { //活动已经结束
                    if (!isClubAdmin) it.remove();
                }
            }
        }
        return list;
    }

    private BigDecimal getActivityMinPrice(TbClubActivity tbClubActivity){
        BigDecimal minPrice = BigDecimal.ZERO;
        int feeType = tbClubActivity.getFeeType();
        if (feeType == 0){      //AA
            minPrice = tbClubActivity.getAaFee();
        }
        if (feeType == 1){      //固定费用
            List<BigDecimal> feeList = new ArrayList<>();
            feeList.add(tbClubActivity.getMaleMemberFee());
            feeList.add(tbClubActivity.getFemaleMemberFee());
            if(tbClubActivity.getSignUpType().equals(Constants.BYTE_ZERO))
            {
                feeList.add(tbClubActivity.getFemaleFee());
                feeList.add(tbClubActivity.getMaleFee());
            }
            minPrice = Collections.min(feeList);
        }
        return minPrice;
    }

    private RespActivityPoster getActivityPoster(Integer posterPicId) {
        RespActivityPoster poster = new RespActivityPoster();
        TbActivityPoster tbActivityPoster = activityPosterMapper.selectByPrimaryKey(posterPicId);
        if (tbActivityPoster != null){
            poster.setId(tbActivityPoster.getId());
            poster.setClubId(tbActivityPoster.getClubId());
            poster.setName(tbActivityPoster.getName());
            poster.setUrl(tbActivityPoster.getUrl());
        }
        return poster;
    }

    @Override
    @Transactional
    public void disableClub(Integer currentUid, Integer clubId) {

        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub == null || tbClub.getIsDelete() == Constants.IS_DELETE_TRUE){
            throw new BizException("此俱乐部已解散！");
        }

        if (tbClub.getUid().intValue() != currentUid){
            throw new BizException("没有权限解散！");
        }

        TbClubOnlineMemberAccountExample onlineEx = new TbClubOnlineMemberAccountExample();
        onlineEx.createCriteria().andClubIdEqualTo(clubId);
        List<TbClubOnlineMemberAccount> onlineMemberAccounts =
                clubOnlineMemberAccountMapper.selectByExample(onlineEx);
        for (TbClubOnlineMemberAccount clubOnlineMemberAccount: onlineMemberAccounts){
            if (clubOnlineMemberAccount.getMoneyTotal().doubleValue() != 0){
                throw new BizException("俱乐部名下还有成员会费未消费完，不能解散！");
            }
        }

        TbClubOnlineAccountExample onlineAccountExample = new TbClubOnlineAccountExample();
        onlineAccountExample.createCriteria()
                .andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOnlineAccount> onlineAccounts = clubOnlineAccountMapper.selectByExample(onlineAccountExample);
        if (onlineAccounts != null && onlineAccounts.size() != 0){
            double money = onlineAccounts.get(0).getMoneyTotal().doubleValue();
            if ( money> 0){
                throw new BizException("俱乐部账户中还有余额￥"+ money + "，请提现后再解散俱乐部！");
            }
        }

        //未取消+有非0元订单报名+未结算 = 不能解散俱乐部
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria()
                .andIsSettleEqualTo((byte)0)           //未结算
                .andActivityStatusNotEqualTo(3f)       //未取消
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);

        List<TbClubActivity> clubActivities = clubActivityMapper.selectByExample(clubActivityExample);
        for (TbClubActivity tbClubActivity : clubActivities) {
            TbOrderExample orderExample = new TbOrderExample();
            orderExample.createCriteria().andActivityIdEqualTo(tbClubActivity.getActivityId())
                    .andOrderStatusIn(Arrays.asList((byte)2, (byte)6, (byte)7));
            if (orderMapper.countByExample(orderExample) > 0){
                throw new BizException("俱乐部还有未结算的活动，不能解散俱乐部！");
            }
        }

        //禁用俱乐部
        tbClub.setIsDelete(Constants.IS_DELETE_TRUE);
        clubMapper.updateByPrimaryKeySelective(tbClub);
        //保留俱乐部线上线下账户，以便后期有数据可查

        //删除俱乐部索引
        APIResponse response = clubSearchService.deleteDocById(clubId);
        if(!response.isRet()){
            logger.warn("解散俱乐部{}，删除索引失败！", clubId);
        }
        //删除俱乐部下的活动索引
        try {
            clubActivityExample.clear();
            clubActivityExample.createCriteria().andClubIdEqualTo(clubId);
            List<TbClubActivity> clubActivityList =  clubActivityMapper.selectByExample(clubActivityExample);
            if (clubActivityList != null && clubActivityList.size() != 0) {
                List<Integer> activityIds = new ArrayList<>();
                for (TbClubActivity clubActivity : clubActivityList) {
                    activityIds.add(clubActivity.getActivityId());
                    activitySearchService.deleteDocsByIds(activityIds);
                }
            }
            TbClubActivity tbClubActivity = new TbClubActivity();       //设置删除状态
            tbClubActivity.setIsDelete((byte)1);
            clubActivityMapper.updateByExampleSelective(tbClubActivity, clubActivityExample);
        }catch (Exception e){
            logger.warn("删除俱乐部{}下的所有活动索引出错, {}", clubId, e.getMessage());
        }

        //删除俱乐部成员
        List<Integer> uids = batchDeleteClubMember(clubId);

        //推送消息给俱乐部成员
        int pageSize = 50;      //推送消息只支持每次推送给50个用户
        int pages = uids.size()/pageSize;
        for (int j = 0; j < pages; j++){
            cppService.pushDisableClub(clubId, uids.subList(j*pageSize, (j+1)*pageSize));
        }
        cppService.pushDisableClub(clubId, uids.subList(pages*pageSize, uids.size()));
    }

    /**
     * 解散俱乐部时，批量删除俱乐部成员
     */
    private List<Integer> batchDeleteClubMember(int clubId){
        //删除tb_club_member
        TbClubMemberExample tbClubMemberExample = new TbClubMemberExample();
        tbClubMemberExample.createCriteria().andClubIdEqualTo(clubId);
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(tbClubMemberExample);
        if (clubMembers == null || clubMembers.size() == 0){
            return new ArrayList<>();
        }
        clubMemberMapper.deleteByExample(tbClubMemberExample);
        //删除俱乐部成员索引，暂时for删除，后面优化提供批量删除方法
        List<Integer> clubMemberUids = new ArrayList<>();
        for (TbClubMember clubMember : clubMembers){
            clubMemberUids.add(clubMember.getUid());
            executor.submit(new ClubMemberSolrIndexThread(clubMember, "", clubMemberSearchService, 2));
        }

        //伪删除tb_club_member_apply
        TbClubMemberApplyExample tbClubMemberApplyExample = new TbClubMemberApplyExample();
        tbClubMemberApplyExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andStatusEqualTo((byte)1); //审核通过加入的
        TbClubMemberApply tbClubMemberApply = new TbClubMemberApply();
        tbClubMemberApply.setIsDelete(Constants.IS_DELETE_TRUE);
        clubMemberApplyMapper.updateByExampleSelective(tbClubMemberApply, tbClubMemberApplyExample);

        //删除tb_club_online_member_account
        TbClubOnlineMemberAccountExample onlineexample = new TbClubOnlineMemberAccountExample();
        onlineexample.createCriteria()
                .andClubIdEqualTo(clubId);
        clubOnlineMemberAccountMapper.deleteByExample(onlineexample);

        //删除tb_club_offline_member_account
        TbClubOfflineMemberAccountExample offlineexample = new TbClubOfflineMemberAccountExample();
        offlineexample.createCriteria()
                .andClubIdEqualTo(clubId);
        clubOfflineMemberAccountMapper.deleteByExample(offlineexample);

        return clubMemberUids;
    }

}
